# -*- coding: utf-8 -*- 

#from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import db
import logging
import datetime
import setting

from model import GroupInfo,GroupSite,_today

site_index = 0

class GetTodayGroups(webapp.RequestHandler):
    def get(self):
        # get date
        today = _today()
        yesterday = today + datetime.timedelta(days=-1)
        logging.info("yesterday %s"%yesterday)

        # get today's group
        groups = GroupInfo.all()
        group_infos = groups.filter('date >', yesterday)

        # sites
        sites = GroupSite.all()
        sites.order('-pop')

        values={
            'sub_title':setting.SUBTITLE,
            'title':setting.TITLE,
            'groups':group_infos,
            'sites':sites,
        }
        
        html = template.render("views/white/index.html",values)
        self.response.out.write(html)

class GenerateAllSiteGroups(webapp.RequestHandler):
    def get(self):
        sites = ['aibang','dianping','doudtuan','fantong','ftuan','lashou','meituan','nuomi','qq','sina','sohu','t55','t58','yuyue']
        for site in sites:
            self.response.out.write('%s started<br>'%site)

            exec('import groups.%s as group'%site)
            
            try:
                group.get_data()
            except:
                pass

            self.response.out.write('%s done<br>'%site)

class GenerateSiteGroups(webapp.RequestHandler):
    def get(self, slug=None):
        if slug == None or slug == '':
            sites = GroupSite.all()
            
            for site in sites:
                self.response.out.write('%s started<br>'%site.code)

                exec('import groups.%s as group'%site.code)
                try:
                    group.get_data()
                except:
                    pass

                self.response.out.write('%s done<br>'%site.code)

        else:
            site_name = slug
            exec('import groups.%s as group'%site_name)
            group.get_data()
        
        self.response.out.write('')
        
class UpdateSiteTotal(webapp.RequestHandler):
    def get(self, slug=None):
        if slug == None or slug == '':
            sites = GroupSite.all().order('name')

            global site_index
            site_index += 1
            logging.info('index %s'%site_index)
            if site_index == sites.count():
                site_index = 0
            
            site = sites[site_index]

            logging.info('site %s'%site.code)

            self.response.out.write('%s started<br>'%site.code)

            exec('import groups.%s as group'%site.code)
            try:
                group.update_site_sold_total()
            except:
                pass

            self.response.out.write('%s done<br>'%site.code)

        else:
            site_name = slug
            
            self.response.out.write('%s started<br>'%site_name)

            exec('import groups.%s as group'%site_name)
            try:
                group.update_site_sold_total()
            except:
                pass

            self.response.out.write('%s done<br>'%site_name)

class UpdateGroupTotal(webapp.RequestHandler):
    def post(self):
        link = self.request.get('link')
        groups = GroupInfo.all()
        group_infos = groups.filter('link =', link)
        if group_infos.count() > 0:
            group_info = group_infos[0]
            exec('import groups.%s as group'%group_info.site.code)
            try:
                group.update_group_sold_total(group_info)
            except:
                pass
            self.response.out.write(group_info.sold_total)
        else:
            self.response.out.write('0')
    def get(self):
        self.response.out.write('0')

class AdminTemp(webapp.RequestHandler):
    def get(self, slug=None):
        self.response.out.write('done')

class UpdateSitePopular(webapp.RequestHandler):
    def get(self, slug=None):
        if slug == None or slug == '':
            self.response.out.write('failed')
            return
        
        group_site = GroupSite.get_by_key_name(slug)
        if group_site:
            group_site.pop = group_site.pop + 1
            group_site.put()
        
        self.response.out.write('succeed')

class GetATOM(webapp.RequestHandler):
    def get(self):
        # get date
        import tools.PyRSS2Gen as PyRSS2Gen

        today = _today()
        yesterday = today + datetime.timedelta(days=-1)
        logging.info("yesterday %s"%yesterday)

        # get today's group
        groups = GroupInfo.all()
        group_infos = groups.filter('date >', yesterday)

        items = []
        for group_info in group_infos:
            item = PyRSS2Gen.RSSItem(
                 title = "%s - %s"%(group_info.site.name,group_info.date),
                 link = group_info.link,
                 description = "<div><img src='%s'>"
                        "<span><a target='_blank' href='%s'>%s</a></span>"
                        "<span><a href='%s' target='_blank' >%s</a></span>"
                        "<span>%s人购买</span>"
                        "<span>现价:<strong>¥%s</strong></span>"
                        "<span>原价:<strong><strike>¥%s</strike></strong></span>"
                        "<span>折扣:<strong><span>%s折</span></strong></span></div>".decode('utf8')%(group_info.site.link,
                        group_info.site.name, group_info.link, group_info.title, group_info.sold_total,
                        group_info.picture, group_info.current_price, group_info.original_price,
                        group_info.discount),
                 guid = PyRSS2Gen.Guid(group_info.link),
                 pubDate = datetime.datetime(group_info.date.year, group_info.date.month, group_info.date.day)),
            items.append(item)

        rss = PyRSS2Gen.RSS2(
            title = setting.TITLE,
            link = setting.ADDRESS,
            description = setting.DESCRIPTION,
            lastBuildDate = datetime.datetime.now(),
            pubDate = datetime.datetime.now(),
            items = items)

        self.response.out.write(rss.to_xml())

class GetRSS(webapp.RequestHandler):
    def get(self):
        # get date
        today = _today()
        yesterday = today + datetime.timedelta(days=-1)
        logging.info("yesterday %s"%yesterday)

        # get today's group
        groups = GroupInfo.all()
        group_infos = groups.filter('date >', yesterday)
        
        last_updated = datetime.datetime.now()
        last_updated = last_updated.strftime("%a, %d %b %Y %H:%M:%S +0000")

        values={
            'sub_title':setting.SUBTITLE,
            'title':setting.TITLE,
            'groups':group_infos,
            'last_updated':last_updated,
        }
        
        html = template.render("views/rss.html",values)
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.response.out.write(html)

class CreateSiteMap(webapp.RequestHandler):
    def get(self):
        urls = []
        def addurl(loc,lastmod=None,changefreq=None,priority=None):
            url_info = {
                'location':   loc,
                'lastmod':	lastmod,
                'changefreq': changefreq,
                'priority':   priority
            }
            urls.append(url_info)

        addurl('http://pythias.appspot.com',changefreq='daily',priority=0.9)

        sites = GroupSite.all()
        for site in sites:
            addurl('http://pythias.appspot.com/tuan/site/%s'%site.code,changefreq='daily',priority=0.5)
        
        today = _today()
        for i in range(30):
            date = today + datetime.timedelta(days=-i)
            addurl('http://pythias.appspot.com/tuan/%s/%s/%s'%(date.year, date.month, date.day),changefreq='daily',priority=0.4)

        html = template.render("views/sitemap.xml",{'urlset':urls})

        self.response.out.write(html)

class GetSiteGroups(webapp.RequestHandler):
    def get(self, slug=None):
        if slug == None or slug == '':
            error_page(self,'请选择站点')
            return
        
        page = self.request.get('p')
        if page == None or page == '':
            page = 1
        else:
            page = int(page)

        # sites
        sites = GroupSite.all()
        sites.order('-pop')

        group_site = GroupSite.get_by_key_name("SITE_%s"%slug)
        if group_site:
            group_infos = group_site.groups
        
            group_count = group_infos.count()
            max_page = group_count / setting.COUNT_PER_PAGE + ( group_count % setting.COUNT_PER_PAGE and 1 or 0 )

            if page < 1 or page > max_page:
                return	error_404(self)

            group_infos = group_infos.order('-date').\
                fetch(setting.COUNT_PER_PAGE, offset = (page-1) * setting.COUNT_PER_PAGE)

            show_prev = group_infos and (not (page == 1))
            show_next = group_infos and (not (page == max_page))

            values={
                'sub_title':setting.SUBTITLE,
                'title':setting.TITLE,
                'groups':group_infos,
                'sites':sites,
                'site':group_site,
                'show_prev':show_prev,
                'show_next':show_next,
                'page_index':page,
            }
            
            html = template.render("views/white/site.html",values)
            self.response.out.write(html)
        else:
            error_page(self,'无法找到站点')


class GetDateGroups(webapp.RequestHandler):
    def get(self, year, month, day):
        
        # get date
        today = datetime.date(int(year), int(month), int(day))
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=+1)

        # get today's group
        groups = GroupInfo.all()
        group_infos = groups.filter('date >', yesterday).filter('date <', tomorrow)

        # sites
        sites = GroupSite.all()
        sites.order('-pop')

        values={
            'sub_title':setting.SUBTITLE,
            'title':setting.TITLE,
            'groups':group_infos,
            'sites':sites,
            'date':'%s年%s月%s日'%(year, month, day),
        }
        
        html = template.render("views/white/date.html",values)
        self.response.out.write(html)

def error_404(req):
    error_page(req, "404")

def error_page(req, msg):
    sites = GroupSite.all()
    sites.order('-pop')
    
    values={
        'sub_title':setting.SUBTITLE,
        'title':setting.TITLE,
        'sites':sites,
        'error_msg':msg,
    }
    html = template.render("views/white/error.html",values)
    req.response.out.write(html)

def main():
    application = webapp.WSGIApplication(
        [
            ('/', GetTodayGroups),                           # 获取今天所有团购
            ('/tuan/', GetTodayGroups),                      # 获取今天所有团购
            ('/tuan/api/all_site', GenerateAllSiteGroups),   # 生成所有预设站点
            ('/tuan/api/site/(.*)', GenerateSiteGroups),     # 生成指定站点/数据库里所有
            ('/tuan/api/update_site/(.*)', UpdateSiteTotal), # 更新制定站点的购买数量
            ('/tuan/api/update_group', UpdateGroupTotal),    # 更新制定团购的购买数量
            ('/tuan/site/(.*)', GetSiteGroups),              # 获取站点的所有团购
            ('/tuan/(\d{4})/(\d{2})/(\d{2})', GetDateGroups),              # 获取某天的所有团购
            ('/admin/temp/(.*)', AdminTemp),                 # 临时测试
            ('/tuan/api/update_pop/(.*)', UpdateSitePopular),# 更新站点的访问量
            ('/tuan/rss', GetRSS),                           # RSS
            ('/tuan/atom', GetATOM),                         # ATOM
            ('/sitemap', CreateSiteMap),                     # SiteMap
            #('/_ah/xmpp/message/chat/', XmppHandler),       # XMPP
        ],
        debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
